package com.alibaba.citrus.cr.mn.order.center.facade.function.assemble.impl.returnorder;

import com.alibaba.citrus.cr.common.enums.GeneralStatusEnum;
import com.alibaba.citrus.cr.common.enums.ordercenter.OrderCategoryEnum;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.BizInventoryQueryAdapter;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.CargoZoneAdapter;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.LogisticWarehouseQueryRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.ItemSearchAbilityDTO;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.LogisticWarehouseQueryDTO;
import com.alibaba.citrus.cr.mn.order.center.facade.function.assemble.OrderBizAssemble;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.mnordercenter.model.dto.ReturnOrderBizCreateRequest;
import com.epoch.app.mnordercenter.model.dto.SalesOrderAtomCreateLineRequest;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author zhangxiaorui
 * @ClassName OrderBizAssembleOfStrategyCenter
 * @description: TODO
 * @date 2023/05/17 09:53
 * @version: 1.0
 */
@Service
@Order(3)
public class ReturnOrderBizAssembleOfInventoryCenter implements OrderBizAssemble<ReturnOrderBizCreateRequest> {
    private static final Log log = Log.getLogger(ReturnOrderBizAssembleOfInventoryCenter.class);

    @Resource
    private BizInventoryQueryAdapter bizInventoryQueryAdapter;

    @Resource
    private CargoZoneAdapter cargoZoneAdapter;

    @Override
    public Map<String, Object> query(ReturnOrderBizCreateRequest exchangeOrderBizCreateRequest) {
        return query(Lists.newArrayList(exchangeOrderBizCreateRequest));
    }

    @Override
    public Map<String, Object> query(List<ReturnOrderBizCreateRequest> exchangeOrderBizCreateRequests) {
        try {
            // Key：库存工厂Code+库存地点Code or 逻辑仓库Code
            Map<String, LogisticWarehouseQueryDTO> logisticWarehouseQueryMap = queryLogisticWarehouseInfoList(exchangeOrderBizCreateRequests);
            Map<String, Object> result = Maps.newHashMap();
            result.put(LOGISTIC_WAREHOUSE, logisticWarehouseQueryMap);
            log.info("销售订单商业能力库存中心数据组装结果 result={}", JSONObject.toJSONString(result));

            return result;
        } catch (Exception e) {
            log.error("销售订单商业能力库存中心数据组装失败", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public Result<String> assemble(Map<String, Object> queryResponseMap, ReturnOrderBizCreateRequest createRequest) {
        // Key：库存工厂Code+库存地点Code or 逻辑仓库Code
        Map<String, LogisticWarehouseQueryDTO> logisticWarehouseMap = getBizInfoMap(queryResponseMap, LOGISTIC_WAREHOUSE, LogisticWarehouseQueryDTO.class);
        // 物料
        Map<String, ItemSearchAbilityDTO> scItemInfoMap = getBizInfoMap(queryResponseMap, SC_ITEM_INFO, ItemSearchAbilityDTO.class);

        for (SalesOrderAtomCreateLineRequest orderDetail : createRequest.getOrderDetails()) {

            // Key：库存工厂Code+库存地点Code or 逻辑仓库Code
            String warehouseKey = orderDetail.getShippingWarehouseCode();
            if (StringUtils.isBlank(warehouseKey)) {
                warehouseKey = String.format("%s_%s", orderDetail.getDeliveryFactoryCode(), orderDetail.getStockCode());
            }
            LogisticWarehouseQueryDTO logisticWarehouseQueryResponse = logisticWarehouseMap.get(warehouseKey);
            if (Objects.isNull(logisticWarehouseQueryResponse)) {
                return Result.fail(createRequest.getSourceOrderNo(),"OC-01-001-01-16-045", "收货仓库地点不存在");
            }
            if (!GeneralStatusEnum.YES.getCode().equals(logisticWarehouseQueryResponse.getStatus())) {
                return Result.fail(createRequest.getSourceOrderNo(),"OC-01-001-01-16-058", "收货仓库地点已禁用");
            }
            orderDetail.setShippingWarehouseCode(logisticWarehouseQueryResponse.getCode());
            orderDetail.setShippingWarehouseName(logisticWarehouseQueryResponse.getName());
            orderDetail.setDeliveryFactoryCode(logisticWarehouseQueryResponse.getSapFactoryCode());
            orderDetail.setStockCode(logisticWarehouseQueryResponse.getWarehouseCode());

            if (OrderCategoryEnum.GROUP.getCode().equals(createRequest.getOrderCategoryCode())){
                if (StringUtils.isNotBlank(orderDetail.getTxWarehouseCode()) || StringUtils.isNotBlank(orderDetail.getTxFactoryCode()) || StringUtils.isNotBlank(orderDetail.getTxStockCode())) {
                    String txWarehouseKey = orderDetail.getTxWarehouseCode();
                    if (StringUtils.isBlank(txWarehouseKey)) {
                        txWarehouseKey = String.format("%s_%s", orderDetail.getTxFactoryCode(), orderDetail.getTxStockCode());
                    }
                    LogisticWarehouseQueryDTO logisticTxWarehouseQueryResponse = logisticWarehouseMap.get(txWarehouseKey);
                    if (Objects.isNull(logisticTxWarehouseQueryResponse)) {
                        return Result.fail(createRequest.getSourceOrderNo(), "OC-01-001-01-16-045", "发货仓库地点不存在");
                    }
                    if (!GeneralStatusEnum.YES.getCode().equals(logisticTxWarehouseQueryResponse.getStatus())) {
                        return Result.fail(createRequest.getSourceOrderNo(), "OC-01-001-01-16-059", "发货仓库地点已禁用");
                    }
                    orderDetail.setTxWarehouseCode(logisticTxWarehouseQueryResponse.getCode());
                    orderDetail.setTxWarehouseName(logisticTxWarehouseQueryResponse.getName());
                    orderDetail.setTxFactoryCode(logisticTxWarehouseQueryResponse.getSapFactoryCode());
                    orderDetail.setTxStockCode(logisticTxWarehouseQueryResponse.getWarehouseCode());
                }
            }

            // 物料信息
            ItemSearchAbilityDTO scItem = scItemInfoMap.get(orderDetail.getProductCode());
            if (Objects.isNull(scItem)) {
                return Result.fail(createRequest.getSourceOrderNo(),"OC-01-001-01-16-012", "物料编码不存在");
            }
            if (!GeneralStatusEnum.YES.getCode().equals(scItem.getStatus())) {
                return Result.fail(createRequest.getSourceOrderNo(),"OC-04-001-01-16-028", "物料编码已禁用");
            }
        }
        return Result.success(null);
    }

    private Map<String, LogisticWarehouseQueryDTO> queryLogisticWarehouseInfoList(List<ReturnOrderBizCreateRequest> returnOrderBizCreateRequests) {
        List<LogisticWarehouseQueryRequest> logisticWarehouseQueryRequests = Lists.newArrayList();
        Set<String> dupLogisticWarehouseCode = Sets.newHashSet();
        Set<String> dupAddressAndFactoryCode = Sets.newHashSet();
        for (ReturnOrderBizCreateRequest createRequest : returnOrderBizCreateRequests) {
            for (SalesOrderAtomCreateLineRequest orderDetail : createRequest.getOrderDetails()) {

                if(StringUtils.isNotBlank(orderDetail.getShippingWarehouseCode())) {
                    if(!dupLogisticWarehouseCode.contains(orderDetail.getShippingWarehouseCode())) {

                        LogisticWarehouseQueryRequest queryRequest = new LogisticWarehouseQueryRequest();
                        queryRequest.setLogicWarehouseCode(orderDetail.getShippingWarehouseCode());
                        logisticWarehouseQueryRequests.add(queryRequest);

                        dupLogisticWarehouseCode.add(orderDetail.getShippingWarehouseCode());
                    }
                } else if(StringUtils.isNotBlank(orderDetail.getDeliveryFactoryCode()) && StringUtils.isNotBlank(orderDetail.getStockCode())) {
                    if(!dupAddressAndFactoryCode.contains(String.format("%s_%s", orderDetail.getDeliveryFactoryCode(), orderDetail.getStockCode()))) {

                        LogisticWarehouseQueryRequest queryRequest = new LogisticWarehouseQueryRequest();
                        queryRequest.setFactoryCode(orderDetail.getDeliveryFactoryCode());
                        queryRequest.setStorageLocation(orderDetail.getStockCode());
                        logisticWarehouseQueryRequests.add(queryRequest);

                        dupAddressAndFactoryCode.add(String.format("%s_%s", orderDetail.getDeliveryFactoryCode(), orderDetail.getStockCode()));
                    }
                }

                if(OrderCategoryEnum.GROUP.getCode().equals(createRequest.getOrderCategoryCode())) {
                    if (StringUtils.isNotBlank(orderDetail.getTxWarehouseCode())) {
                        if (!dupLogisticWarehouseCode.contains(orderDetail.getTxWarehouseCode())) {

                            LogisticWarehouseQueryRequest queryRequest = new LogisticWarehouseQueryRequest();
                            queryRequest.setLogicWarehouseCode(orderDetail.getTxWarehouseCode());
                            logisticWarehouseQueryRequests.add(queryRequest);

                            dupLogisticWarehouseCode.add(orderDetail.getTxWarehouseCode());
                        }
                    } else if (StringUtils.isNotBlank(orderDetail.getTxFactoryCode()) && StringUtils.isNotBlank(orderDetail.getTxStockCode())) {
                        if (!dupAddressAndFactoryCode.contains(String.format("%s_%s", orderDetail.getTxFactoryCode(), orderDetail.getTxStockCode()))) {

                            LogisticWarehouseQueryRequest queryRequest = new LogisticWarehouseQueryRequest();
                            queryRequest.setFactoryCode(orderDetail.getTxFactoryCode());
                            queryRequest.setStorageLocation(orderDetail.getTxStockCode());
                            logisticWarehouseQueryRequests.add(queryRequest);

                            dupAddressAndFactoryCode.add(String.format("%s_%s", orderDetail.getTxFactoryCode(), orderDetail.getTxStockCode()));
                        }
                    }
                }
            }
        }

        if(CollectionUtils.isEmpty(logisticWarehouseQueryRequests)) {
            return Maps.newHashMap();
        }

        List<LogisticWarehouseQueryDTO> listResult = cargoZoneAdapter.queryCargoZoneListByParam(logisticWarehouseQueryRequests);
        if(CollectionUtils.isEmpty(listResult)) {
            return Maps.newHashMap();
        }

        Map<String, LogisticWarehouseQueryDTO> logisticWarehouseQueryResponseMap = Maps.newHashMap();
        for (LogisticWarehouseQueryDTO logisticWarehouseQueryResponse : listResult) {
            String factoryStockCode = String.format("%s_%s", logisticWarehouseQueryResponse.getSapFactoryCode(), logisticWarehouseQueryResponse.getWarehouseCode());
            logisticWarehouseQueryResponseMap.put(factoryStockCode, logisticWarehouseQueryResponse);
            logisticWarehouseQueryResponseMap.put(logisticWarehouseQueryResponse.getCode(), logisticWarehouseQueryResponse);
        }

        return logisticWarehouseQueryResponseMap;
    }
}
